<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: LoginOpenId.php 425 2011-01-05 10:30:30Z steen.rabol $
 *
 */

Prado::using('Application.Common.Data.PortalUserOpenIdRecord');
Prado::using('Application.Common.Data.PortalUserRecord');
Prado::using('Application.Common.PortalOpenId');

class LoginOpenId extends PortalSystemPage
{
	private $_action;

	public function onInit($param)
	{
		parent::onInit($param);
		$this->Page->getClientScript()->registerFocusControl($this->openid_url);
		$this->Action	= $this->Request['action'];

		if($this->Action !== null)
		{
			$this->pnlLogin->Enabled	= false;
			$this->pnlLogin->Visible	= false;
		}
	}

	public function onLoad($param)
	{
		parent::onLoad($param);

		if($this->Action == 'oidok')
		{
			$this->pnlLogin->Enabled	= false;
			$this->pnlLogin->Visible	= false;

			$poid			= new PortalOpenId();
			$returntourl	= $this->Request->BaseUrl . $this->Service->constructUrl('System.LoginOpenId',array('action' => 'oidok'));
			$trusturl		= $this->Request->BaseUrl . '/';
			$sreg 			= $poid->CompleteVerifyOpenId($returntourl);

			if($sreg)
			{
				$oid			= $this->Session->itemAt('ver_openidurl');
				$uid			= PortalUserOpenIdRecord::GetUserId($oid);
				$username		= PortalUserOpenIdRecord::GetUserName($uid);
				$authManager	= $this->Application->getModule('auth');
				if(!$authManager->login($username,$this->Application->Parameters['OpenIdPassword']))
				{
					$this->reportError(0,"Faild to login using OpenId {0}",array($oid));
				}
				$this->gotoDefaultPage();
			}
		}
	}

	public function loginButtonClicked($sender,$param)
	{
		if($this->Page->IsValid)
		{
			$this->pnlLogin->Enabled	= false;
			$this->pnlLogin->Visible	= false;

			$poid			= new PortalOpenId();
			$returntourl	= $this->Request->BaseUrl . $this->Service->constructUrl('System.LoginOpenId',array('action' => 'oidok'));
			$trusturl		= $this->Request->BaseUrl . '/';
			$this->Session->add('ver_openidurl',$this->openid_url->Text);
			$sreg = $poid->VerifyOpenId($this->openid_url->Text,$trusturl,$returntourl);
		}
	}

	public function checkOpenIdUrl($sender,$param)
	{
		$uid = PortalUserOpenIdRecord::GetUserId($param->Value);
		if($uid == 0)
		{
			$param->IsValid = false;
		}
		else
		{
			$param->IsValid = true;
		}
	}

	public function getAction()
	{
		return $this->_action;
	}

	public function setAction($value)
	{
		$this->_action = $value;
	}

	public function CancelButtonClicked($sender,$param)
	{
		$this->gotoDefaultPage();
	}
}
?>